<?php

class homeAction extends BaseAction {
    
    private function getSinaAppConn(){
        
        include_once(ROOT. '/cgi/sina/config.php' );
        include_once(ROOT. '/cgi/sina/weibooauth.php' );

        return  new WeiboClient( WB_AKEY , WB_SKEY ,  token_key, token_secret);
    }
    
    public function actionGo() {
        echo get_block('home', 'access');
    }
    
    /**
     * 获取网址
     * @param <type> $uhash
     * @return string
     */
    public function getUrl($uhash) {
        $url = getHashUrl($uhash);
        if (empty($url)) {
            $acc = DAO_Finder::findOne(DB_URL, array('uhash' => "$uhash"), 'url');
            if (!empty($acc)) {
                $url = $acc->getUrl();
                $url->save();
            } else {
                return null;
            }
        }
        return $url;
    }
    
    public function actionAccess() {
        //header('Content-Type:text/html;charset:utf-8');
        define('DEBUG', false);

        $uhash = getRequestUhash();
        $uhash  = $this->params['uhash'];

        $url = $this->getUrl($uhash);

        if($url == null) {
            $this->redirect('/');
        }else{
            header('HTTP/1.0 302 FOund');
            header('Location: '.$url);
        }


        if (empty($_SESSION['tmp']['uid'])) {
            $uid = 0;
        } else {
            $uid = $_SESSION['tmp']['uid'];
        }
        $ip = getIp();
        $time   = date('Ymd');
        //记录PV
        //$acc    = DB_ACCESS::writeAccess($uhash);
        //$sql = "call updateCountVoid('$uhash','$ip',$uid); " . getBr();
        //记录今日pv
        //DB_COUNT_PV::writeTodayPv($uhash);
        
        /**
         * 记录当前时段PV
         */
        
        /**
         * 记录当前时段pv
         */
        DB_COUNT_PV_HOUR::writeTodayPv($uhash);
        DB_COUNT_PV::writeTodayPv($uhash);
//        
//        $sql    = "INSERT u22_count_pv (uhash,log_time,uid) VALUES(?,?,?)  ON DUPLICATE KEY UPDATE pv=pv+1";
//        $exec   = DAO_Finder::exec($sql, 'DB_IP', array($uhash,$time,$uid));

        $total  = DAO_Finder::findCount('DB_IP', array('uhash' => $uhash,'ip' => $ip), 'id');

        $uid = 0;
        
        $url_obj    = ORM_Finder::findOne('DB_URL', array('uhash'=>$uhash));
        $total_pv   = $url_obj->getTotalPv() +1;
        //独立的IP
        if($total == 0) {
            
            //IP+1
            $total_ip   = $url_obj->getTotalIp() + 1;
            $url_obj->setTotalIp($total_ip);
            $url_obj->setTotalPv($total_pv);
            $url_obj->save();
            
            //写入新的ip
            $u22_ip = new DB_IP();
            $u22_ip->setUhash($uhash);
            $u22_ip->setIp($ip);
            $u22_ip->setCreated(time());
            $u22_ip->setUid($uid);
            $u22_ip->save();
            
            DB_COUNT_IP_HOUR::writeTodayIp($uhash);
            DB_COUNT_IP::getTableName();

        }else{
            
            $url_obj->setTotalPv($total_pv);
            $url_obj->save();           
        }

        //记录访问
        $acc    = DB_ACCESS::writeAccess($uhash);

        //记录操作系统
        $os = getOsName();
        //FileWrite::writeTableOs($uid, $uhash, $os);
        $sql= "INSERT u22_url_os (uid,uhash, name) values (?,?, ?) ON DUPLICATE KEY UPDATE click=click+1";
        DAO_Finder::exec($sql,DB_USER,array($uid, $uhash, $os));

        $debug[]  = array('sql' =>$sql, 'param' => array($uid, $uhash, $os));
        //来源
        //$referer    = getReferer();
        //$referer    = Common::pregDomain($rederer);;
        //FileWrite::writeTableReferer($uid, $uhash, $referer);
        
        //记录浏览器
        $ie = getIeName();
        //FileWrite::writeTableIe($uid, $uhash, $ie);
        $sql= "INSERT u22_url_ie (uid,uhash, name) values (?,?, ?) ON DUPLICATE KEY UPDATE click=click+1";
        DAO_Finder::exec($sql, 'DB_USER', array($uid, $uhash, $ie));

        $debug[]  = array('sql' =>$sql, 'param' => array($uid, $uhash, $ie));
        
        //记录蜘蛛
        $spider = getRoots();
        //FileWrite::writeTableSpider($uid, $uhash, $spider);
        if(!empty($spider)) {
            $sql    = "INSERT u22_url_spider (uid,uhash, name) values (?,?,?) ON DUPLICATE KEY UPDATE click=click+1";
            DAO_Finder::exec($sql,  'DB_USER', array($uid, $uhash, $spider));
            $debug[]  = array('sql' =>$sql, 'param' => array($uid, $uhash, $spider));
        }

        $ip = getIp();
        $diqu    = convertip($ip);
        $list_arra  = array(
            '北京','天津','上海', '重庆','河北','山西','辽宁','吉林 ','黑龙江','江苏','浙江','安徽','福建 ',
            '江西 ','山东 ','河南 ','湖北',' 湖南',' 广东',' 海南','四川',' 贵州',' 云南',' 陕西',' 甘肃',
            '青海',' 台湾','广西','内蒙古','西藏','宁夏','新疆','香港','澳门');
        
        $pro    = null;
        foreach ($list_arra as $k => $v) {
            $v  = trim($v);
            if(preg_match('~'.$v.'~', $diqu)){
                $pro    = $v;
                break;
            }
        }
        
        if($pro == null){
            $pro    == '其他';
        }

        //省份
        //FileWrite::writeTableProvince($uid, $uhash, $local['province']);
        $sql    = "INSERT u22_url_province (uid,uhash, name) values (?,?,?) ON DUPLICATE KEY UPDATE click=click+1";
        //$pro    = $local['province'];
        $insert = array($uid, $uhash, $pro);
        DAO_Finder::exec($sql, 'DB_USER', $insert);

    }

    public function actionIndex() {
        set_time_limit(60);
        if(array_key_exists('user', $_SESSION)){
            $this->redirect('user');
        }
        $this->view->layout = 'u22';

        $rs = Cookies::getMine('u22_url');
        //$rs = "'". str_replace(',', "','", $rs) ."'";
        $rs = explode(',', $rs);
        $cb = array();
        $w  = null;
        if(count($rs) > 0) {
            for($i=0;$i<count($rs);$i++) {
                $cb[]   = '?';
            }
            $w  = implode(',', $cb);
        }
        $sql    = "select * from {#prefix#}url where uhash in (". $w.") order by id desc";
        $re = DAO_Finder::result($sql, DB_URL, $rs);
        if(empty($re)) {
            Cookies::remove('u22_url');
        }
        $this->set('rs', $re);
        $this->render();
    }
    
    public function actionIndexNew() {
        if(array_key_exists('user', $_SESSION)){
            $this->redirect('user');
        }
        $this->view->layout = 'u22_new';
        $this->render();
    }

    /**
     * 腾讯微博登陆
     */
    public function actionTencentLogin(){
        
        if(empty($_SESSION['weibo']['tencent'])) {
            exit('非法访问');
        }
        unset ($_SESSION['app_key_tencent']);
        
        $tencent    = $_SESSION['weibo']['tencent']['data'];
        $email      = $tencent['email'];
        $email   = $tencent['name'].'@qq';
        $has    = DB_USER::hasEmail($email);
        //未注册
        if(!$has){
            $pass   = Common::getPassword('123');
            $user   = new DB_USER();
            $user->setEmail($email);
            $user->setLevel(1);
            $user->setPassword($pass);
            $user->setIsActive(0);
            $user->save();
            $_SESSION['user']   = $user->getArray();
        }else{
            $_SESSION['user']   = $has->getArray();
        }
        //保存appkey
        if(!empty($_SESSION['last_key_tencent'])){
            $key    = $_SESSION['last_key_tencent'];
            DB_APP_KEY_TENCENT::setUpdate($key['oauth_token'], $key['oauth_token_secret'],$_SESSION['user']['id'], $tencent['name']);
        }

        get_block('home', 'set_url_uid');
        $this->redirect('user/');
    }

    /**
     * 新浪登陆，重置密码
     */
    public function actionSinaLogin(){
        if(!array_key_exists('last_key_sina', $_SESSION)){
            exit('非法访问');
        }
        //$has    = DB_APP_KEY_SINA::setUpdate($_SESSION['last_key_sina']['oauth_token'], $_SESSION['last_key_sina']['oauth_token_secret'], 0, $_SESSION['last_key_sina']['user_id']);
        
        
        $email  = $_SESSION['last_key_sina']['user_id'];
        $email   = $_SESSION['last_key_sina']['me']['screen_name'];
        $has    = DB_USER::hasEmail($email);
        if(!$has){
            $pass   = Common::getPassword('123');
            $has   = new DB_USER();
            $has->setEmail($email);
            $has->setLevel(1);
            $has->setPassword($pass);
            $has->setIsActive(0);
            $has->save();
            $_SESSION['user']   = $has->getArray();
        }else{
            $_SESSION['user']   = $has->getArray();
         }
        //保存appkey
        if(!empty($_SESSION['last_key_sina'])){
            $key    = $_SESSION['last_key_sina'];
            DB_APP_KEY_SINA::setUpdate($key['oauth_token'], $key['oauth_token_secret'],$has->getId(), $has->getEmail());
        }
        get_block('home', 'set_url_uid');
        
       $this->redirect('user/index');
    }

    /**
     * 重置密码
     */
    public function actionResetPassword() {

        $password   = $this->postVar('password');
        $email   = $this->postVar('email');
        $password   = Common::getPassword($password);

        if($email && $password) {
            $user   = new DB_USER();
            $user->setEmail($email);
            $user->setPassword($password);
            $user->save();
            $user   = $user->getArray();
            $this->setSession('user', $user);

            if(array_key_exists('sina_id', $_SESSION)) {
                $sina   = DAO_Finder::findById(DB_APP_KEY_SINA, $_SESSION['sina_id']);
                $sina->setUid($_SESSION['sina_id']);
                $sina->save();
                unset($_SESSION['sina_id']);
            }    
            echo 'ok';
            exit;
        }
        echo 'error';
    }

    public function actionNotFound() {
        echo 'the page not found!';
    }
    
    function actionShowShareStatusesWeibo(){
        $this->setPageTitle('查询指定单个短链接的最新微博内容');
        $this->view->layout = '';
        $url    = trim($this->params['url']);
        $u    = 'http://t.cn/';
        
        if(empty($url)) {
            $u    .= 'hIXSg';
            $this->render('show_share_statuses_weibo_index');
            exit;
        }else{
            $u      .=$url;
        }
        
        $re = array();
        
        if(!empty($url)) {
            $c      = $this->getSinaAppConn();
            $parameters = array('count'=>'20');
            $parameters = array('page'=>'1','count'=>200);
            if(isset($_SESSION['id'])){
                //$parameters['since_id'] = $_SESSION['id'];
            }
            $re     = $c->short_url_share_statuses($u, $parameters);

        }
        $this->set('url', $url);
        $this->set('rs', $re);
        $this->render();
    }
    
    function actionShowShareStatusesComment(){
        $this->setPageTitle('查询指定单个短链接的最新微博评论');
        $url    = $this->getVar('url');
        $u    = 'http://t.cn/';
        if(empty($url)) {
            $u    .= 'hIXSg';
        }else{
            $u      .=$url;
        }
        
        $re = array();
        if(!empty($url)) {
            $c      = $this->getSinaAppConn();
            $parameters = array('count'=>'200');
            if(isset($_SESSION['id'])){
                //$parameters['since_id'] = $_SESSION['id'];
            }
            $re     = $c->short_url_comment_comments($u,$parameters);
        }
        $this->set('rs', $re);
        $this->render();
    }
    
    function actionShowWeiboComment(){
        $id = $this->params['id'];
        $c  = $this->getSinaAppConn();
        $re = $c->get_comments_by_sid($id, 1, 20);
        print_r($re);
    }
    
    function actionTest(){
        $url    = 'http://www.baidu.com/';
        getasdsa(213123213);
        
        
    }
}

